package com.example.xyr.myapplication.utils;

import com.jrmf360.tools.utils.LogUtil;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @创建人 honglin
 * @创建时间 2017/11/3 下午5:42
 * @类描述 获得收银台签名
 */
public class JrmfSignUtil {

    /**
     * 获得收银台签名的方法
     * @param params
     * @return
     */
	public static String paySign(Map<String, String> params) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		StringBuffer sb = new StringBuffer();
		int count = keys.size();
		for (String s : keys) {
			if (!hasNullStr(params.get(s))) {
				sb.append(s);
				sb.append(":");
				sb.append(params.get(s));
				if (count > 1) {
					sb.append("|");
				}
			}
			count--;
		}

		LogUtil.e();
		String sign = "";
		try {
			LogUtil.e(sb.toString());
			sign = toHexValue(encryptMD5(sb.toString().getBytes(Charset.forName("utf-8"))));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("md5 error");
		}
		System.out.println("sign:" + sign);
		return sign;
	}

	public static String sign(String params){
		String sign = "";
		try {
			LogUtil.e(params);
			sign = toHexValue(encryptMD5(params.getBytes(Charset.forName("utf-8"))));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("md5 error");
		}
		System.out.println("sign:" + sign);
		return sign;
	}

	private static String toHexValue(byte[] messageDigest) {
		if (messageDigest == null) return "";
		StringBuilder hexValue = new StringBuilder();
		for (byte aMessageDigest : messageDigest) {
			int val = 0xFF & aMessageDigest;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	private static byte[] encryptMD5(byte[] data) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(data);
		return md5.digest();
	}

	private static boolean hasNullStr(String arg) {
		return arg == null || arg.trim().equals("") || arg.trim().equalsIgnoreCase("null");
	}
}
